﻿using Dapper;
using Himp.TaskScheduling.Hangfire.Jobs;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using System.Data;

namespace Himp.TaskScheduling.Hangfire
{
    /// <summary>
    /// 煤样抽样任务
    /// </summary>
    public class SampleSpotCheckJob : IHostedService
    {
        #region SQL

        public const string GET_SAMPLE_SPOT_CHECK_SQL = @"
                                                        SELECT
                                                        *
                                                        FROM
                                                        sampling_task_table
                                                        where stas=N'待执行'
                                                        ";

        public const string UPDATE_SAMPLE_SPOT_CHECK_SQL = @"
                                                        UPDATE
                                                        sampling_task_table
                                                        SET 
                                                        stas=N'已执行'
                                                        WHERE id=@id
                                                        ";

        public const string INSERT_STANDARD_TEST_TASK_SQL = @"
            INSERT INTO
            [TaskScheduling].[TS_SampleTestTasks]
            (
            SampleCode,
            TestCode,
            BottomCode,
            Sampletype,
            TestCnt,
            TaskAssgnTime,
            LastOperTime,
            TestItems,
            ExecStas,
            ManualFlag
            )
            VALUES
            (
            @SampleCode,
            @TestCode,
            @BottomCode,
            @Sampletype,
            @TestCnt,
            GETDATE(),
            GETDATE(),
            @TestItems,
            @ExecStas,
            @ManualFlag
            )
            ";

        #endregion

        #region 字段

        private readonly ConnectionStringOption _connectionStrings;
        private ILogger<SampleSpotCheckJob> _logger;

        #endregion

        #region 方法

        public SampleSpotCheckJob(ILogger<SampleSpotCheckJob> logger
            , IOptions<ConnectionStringOption> connectionStrings)
        {
            _logger = logger;
            _connectionStrings = connectionStrings.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("--------启动:煤样抽样任务下发--------");

            try
            {
                using (IDbConnection connection = new SqlConnection(_connectionStrings.RL_Web))
                {
                    connection.Open();
                    // 读取数据
                    var standardTestTaskResultList = connection.Query<SampleSpotCheckModel>(GET_SAMPLE_SPOT_CHECK_SQL);

                    foreach (var item in standardTestTaskResultList)
                    {
                        var testItems = "";
                        SampleTestTask sampleTestTask = new SampleTestTask(item.sample_code
                            , item.assay_code ?? item.sample_code
                            , item.coal_sample_code
                            , "3"
                            , 2
                            , testItems
                            , 0);

                        var insertStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL, sampleTestTask);
                        var updateStas = await connection.ExecuteAsync(UPDATE_SAMPLE_SPOT_CHECK_SQL, new { ID = item.id });
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(exception: e, "异常:自动存样1柜信息同步");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        #endregion
    }

    public class SampleSpotCheckModel
    {
        public long id { get; set; }

        public string sample_code { get; set; }

        public string assay_code { get; set; }

        public string coal_sample_code { get; set; }
    }
}
